<template>
  <div class="index_container">
    <div class="container">
      <el-form inline :model="formData">
        <el-form-item prop="time">
          <el-date-picker
              v-model="formData.time"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="yyyy-MM-dd"
              :picker-options="pickerOptions"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button @click="changeClick" class="staff_btn">搜索</el-button>
        </el-form-item>
        <el-form-item prop="styleList">
          <el-select
              v-model="chioce_style_number"
              placeholder="搜索后可过滤数据"
              @remove-tag="style_change"
              class="input-100"
              multiple
              @change="changeSearch"
          >
            <el-option
                v-for="item in style_number"
                :key="item"
                :value="item"
                :label="item"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <el-button @click="tableToExcel">导出</el-button>
      <el-button class="staff_btn" @click="settleAccounts">结算</el-button>
    </div>
    <div>
      <el-table
          :data="new_table_data"
          border
          @selection-change="handleSelectionChange"
          style="width: 100%">
        <el-table-column
            prop="username"
            label="员工名称"
            width="180">
        </el-table-column>
        <el-table-column
            v-for="(item, index) in style_number"
            :key="index"
            v-if="chioce_style_number.includes(item)"
            :prop="item"
            :label="item"
            width="180">
        </el-table-column>
        <el-table-column
            prop="total_amount"
            label="总金额">
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
                size="mini"
                type="primary"
                @click="handleEdit(scope.$index, scope.row)">
              结算
            </el-button>
          </template>
        </el-table-column>
        <el-table-column
            type="selection"
            width="55">
        </el-table-column>
      </el-table>

    </div>
  </div>
</template>

<script>
import {getSalaryBrowse, settleAccounts} from "@/request/api/overview/overview";
import myTabel from "@/components/myTable/index.vue";
import dayjs from "dayjs";
import {getLastWeekDate} from "@/utils/latelyTime";

export default {
  components: {myTabel},
  data() {
    const _this = this;
    return {
      chioce_style_number: [],
      isAllChecked: false,
      isIndeterminate: true,
      activeName: '1',
      isVisible: false,
      showMyTable: true,
      formData: {
        id: "",
        time: [],
        styleList: "",
      },
      columnData: [],
      title: "",
      list: [],
      tableData: [],
      formListData: [],
      style_number: [],
      new_table_data: [],
      selectAll: false,
      multipleSelection: [],
      //最大为当天
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
      },
    };
  },
  created() {
    // 默认一周内
    this.formData.time = getLastWeekDate();
    this.changeClick();
  },

  methods: {
    tableToExcel() {
      const jsonData = this.new_table_data
      const column = [
        {label: '员工名称', prop: 'username'},
      ];

      this.chioce_style_number.forEach(item => {
        column.push({label: item, prop: item})
      })
      column.push({label: '总金额', prop: 'total_amount'})


      // // 列标题
      let worksheet = 'sht1';
      let str = '<tr>';
      //
      column.forEach(item => {
        str += `<td>${item.label}</td>`;
      });

      str += '</tr>';
      console.log("🚀 ~ file:col method:tableToExcel line:152 -----", column)

      // 循环遍历，每行加入tr标签，每个单元格加td标签
      for (let i = 0; i < jsonData.length; i++) {
        str += '<tr>';
        console.log("🚀 ~ file:col method:tableToExcel line:152 -----", column)
        // 增加\t为了不让表格显示科学计数法或者其他格式 item2.str.slice(0,2)+' | '+item2.str.slice(2)
        for (let j = 0; j < column.length; j++) {
          console.log("🚀 ~ file:overview method:tableToExcel line:158 -----", column[j].prop)
          if (jsonData[i][column[j].prop]) {
            str += `<td>${jsonData[i][column[j].prop]}</td>`;
          } else {
            str += `<td>/</td>`;
          }
        }


        str += '</tr>';
      }
      // 下载的表格模板数据
      let template = `<html xmlns:o="urn:schemas-microsoft-com:office:office"
    xmlns:x="urn:schemas-microsoft-com:office:excel"
    xmlns="http://www.w3.org/TR/REC-html40">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <head><!--[if gte mso 9]><xml encoding="UTF-8"><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>
    <x:Name>${worksheet}</x:Name>
    <x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet>
    </x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]-->
    </head><body><table>${str}</table></body></html>`;

      // 调用文件下载函数
      const downloadFile = (content, filename) => {
        const link = document.createElement('a');
        link.href = URL.createObjectURL(new Blob([content], {type: 'application/vnd.ms-excel'}));
        link.download = filename;
        link.style.display = 'none';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      };


      //今天的日期
      let date = new Date()
      let year = date.getFullYear()
      let month = date.getMonth() + 1
      let day = date.getDate()
      let hour = date.getHours()
      let minute = date.getMinutes()


      let templateName = `${year}-${month}-${day} ${hour}时${minute}分.xls`
      downloadFile(template, templateName);
    },
    style_change() {
      console.log(this.chioce_style_number)
    },
    async handleEdit(index, row) {
      console.log("🚀 ~ file:overview method:handleEdit line:191 -----", index, row)
      // 结算按钮的点击事件处理逻辑
      console.log(index, row)
      let pruduct_id_list = []
      const employee_id = row.employee_id;
      row.details.forEach((item) => {
        if (this.chioce_style_number.includes(item.style_number)) {
          pruduct_id_list.push(item.product_id)
        }
      })
      const product_id = pruduct_id_list.join(",");

      const start_time = this.formData.time[0];
      const end_time = this.formData.time[1];
      console.log("employee_id:", employee_id)
      console.log("product_id:", product_id)
      const data = {
        employee_id, product_id, start_time, end_time
      }
      const res = await settleAccounts(data)
      if (res.code == 200) {
        console.log("🚀 ~ file:overview method:handleEdit line:204 -----", data)
        this.$message({
          message: res.message,
          type: "success"
        })
      }
    },
    //多选结算
    async settleAccounts() {
      // 结算按钮的点击事件处理逻辑
      let pruduct_id_list = []
      const employee_id = this.multipleSelection.map(item => item.employee_id).join(",")


      this.multipleSelection.forEach((item) => {
        item.details.forEach((item) => {
          if (this.chioce_style_number.includes(item.style_number) && pruduct_id_list.indexOf(item.product_id) == -1) {
            pruduct_id_list.push(item.product_id)
          }
        })
      })


      const product_id = pruduct_id_list.join(",");
      const start_time = this.formData.time[0];
      const end_time = this.formData.time[1];
      console.log("employee_id:", employee_id)
      console.log("product_id:", product_id)
      const data = {
        employee_id, product_id, start_time, end_time
      }
      const res = await settleAccounts(data)
      if (res.code == 200) {
        console.log("🚀 ~ file:overview method:handleEdit line:204 -----", data)
        this.$message({
          message: res.message,
          type: "success"
        })
      }
    },


    updateIsAllChecked() {
      this.isAllChecked = this.new_table_data.every((item) => item.checked);
    },
    // 增加款式新的table_Data
    addKeyValuePair(data) {
      console.log(data, 'addKeyValuePair')
      data.forEach(item => {
        item.details.forEach(detail => {
          const key = detail.style_number;
          const value = detail.salary;
          // 使用 Vue.set 方法将新属性设置为响应式属性
          this.$set(item, key, value);
        });
      });
      this.new_table_data = data;
      console.log("new_table_data", this.new_table_data)
    },

    // 获取工资计算列表数据
    changeClick() {
      const start_time = this.formData.time[0];
      const end_time = this.formData.time[1];
      const data = {
        start_time,
        end_time,
      };
      this.columnData = [];

      getSalaryBrowse(data).then((res) => {
        console.log("🚀 ~ file:overview method: line:240 -----res", res)
        // j计算总价
        this.tableData = res.data.map((obj) => {
          console.log("🚀 ~ file:overview method: line:243 -----", obj)
          let total_price = 0;
          // for (let key in obj.details) {
          //   if (key === "salary") {
          //     total_price += parseFloat(obj.details[key]);
          //   }
          // }
          for (let i = 0; i < obj.details.length; i++) {
            total_price += parseFloat(obj.details[i].salary);// 为什么这里不用key
          }
          console.log("🚀 ~ file:overview method: line:253 -----", {...obj, total_amount: total_price.toFixed(2)})
          return {...obj, total_amount: total_price.toFixed(2)};
        });
        console.log("🚀 ~ file:overview method: line:254 -----", this.tableData)
        // 单独存储用来 过滤数据
        this.list = res.data;
        // 提取过滤用的表头
        this.formData.styleList = [
          ...new Set(res.data.map((item) => item.style_number)),
        ];
        // 提取表头
        const keys = Array.from(
            new Set(res.data.flatMap((obj) => Object.keys(obj)))
        );
        const dataList = keys.map((item) => {
          let obj = {};
          if (item === "username") {
            obj = {
              prop: item,
              label: "员工名称",
              "min-width": "100",
            };
          } else {
            obj = {
              prop: item,
              label: item,
              "min-width": "100",
            };
          }
          return obj;
        });
        this.columnData = dataList.concat(this.columnData);
        this.extractStyleNumbers(this.tableData)// 获取所有款式且不重复
        this.addKeyValuePair(this.tableData)// 增加款式新的table_Data
        this.chioce_style_number = this.style_number
        console.log("dataList", dataList)
        console.log("tableData", this.tableData)

      });

    },

    // 过滤列表数据
    changeSearch(val) {
      if (val.length !== 0) {
        this.tableData = this.list.filter((item) =>
            val.includes(item.style_number)
        );
      } else {
        this.changeClick();
      }
    },
    handleSelectionChange(val) {
      console.log(val)
      // 已勾选的行赋值
      this.multipleSelection = val
    },
    // 获取所有款式且不重复
    extractStyleNumbers(data) {
      const styleNumberSet = new Set();

      for (let i = 0; i < data.length; i++) {
        for (let j = 0; j < data[i].details.length; j++) {
          styleNumberSet.add(data[i].details[j].style_number)
        }
      }

      this.style_number = Array.from(styleNumberSet);
    },
    incloud_style_number(item) {
      console.log("incloud_style_number传入参数:", item, this.chioce_style_number.includes(item))

      return this.chioce_style_number.includes(item)
    }
  },
  mounted() {

    this.formData.time = [
      dayjs().startOf("month").format("YYYY-MM-DD"),
      dayjs().endOf("month").format("YYYY-MM-DD"),
    ]

    this.changeClick();
  },
  computed: {
    // incloud_style_number(item) {
    //   console.log("incloud_style_number传入参数:",item.toString())
    //   return true
    // }
  },
  watch: {
    chioce_style_number: {
      deep: true,
      handler(newVal, oldVal) {
        this.new_table_data = this.new_table_data.map((obj) => {
          let total_price = 0;
          // for (let key in obj.details) {
          //   if (key === "salary") {
          //     total_price += parseFloat(obj.details[key]);
          //   }
          // }
          for (let i = 0; i < obj.details.length; i++) {
            if (newVal.includes(obj.details[i].style_number)) {
              total_price += parseFloat(obj.details[i].salary);
            }
          }
          return {...obj, total_amount: total_price.toFixed(2)};
        })
        console.log(this.new_table_data)
      }
    },
    new_table_data: {
      handler() {
        this.updateIsAllChecked();
      },
      deep: true,
    },
  }
};
</script>

<style lang="scss">
.container {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.staff_title {
  font-size: 24px;
  font-weight: 500;
}

.el-form {
  height: 40px;
  line-height: 40px;

  .el-range-editor.el-input__inner {
    padding: 0 10px;
  }

  .input-100 {
    .el-input__inner {
      width: 350px;
    }
  }
}

.staff_btn {
  height: 32px;
  line-height: 10px;
}

.dialog_content {
  width: 400px;
  margin: 0 auto;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
